package com.mframe.persist;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.SaveOrUpdateEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mframe.system.LoginInfo;
import com.mframe.system.SystemManager;

/**
 * @author cuijr
 * 在hibernate保存和修改的时候对用户信息进行同步
 */
public class SetTimeAndUserListener implements SaveOrUpdateEventListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = LoggerFactory
	.getLogger(SetTimeAndUserListener.class);
	public void onSaveOrUpdate(SaveOrUpdateEvent event)
			throws HibernateException {
		Object object = event.getObject();
		if (object instanceof RecordUserAndTimeAble) {
			Date date = new Date();
			LoginInfo loginInfo = (LoginInfo) SystemManager.getLoginInfo();
			String staffName = (loginInfo != null) ? loginInfo.getStaffName()
					: null;
			RecordUserAndTimeAble entity = (RecordUserAndTimeAble) object;

			if (entity.getCreateTime() == null) {
				if("".equals(entity.getCtreateUser().trim())||null==entity.getCtreateUser()){
					entity.setCreateUser(staffName);
				}
				entity.setCreateTime(date);
				entity.setUpdateTime(date);
				entity.setUpdateUser(staffName);
				logger.debug("{}对象 被 {} 在 {} 创建", new Object[] { object,
						staffName, date });
			} else {
				entity.setUpdateTime(date);
				entity.setUpdateUser(staffName);
				logger.debug("{}对象 被 {} 在 {} 修改", new Object[] { object,
						staffName, date });
			}
		}
	}

}
